Skip to content

[lexical][lexical-clipboard][lexical-code-core][lexical-code-prism][lexical-code-shiki][lexical-eslint-plugin][lexical-extension][lexical-list][lexical-playground][lexical-react][lexical-table][lexical-y] Feature: flag accidental nested editor updates - #9106

Open
ZedingZhang wants to merge 11 commits into
meta:mainfrom
ZedingZhang:feature/no-nested-editor-updates

Conversation

@ZedingZhang

@ZedingZhang ZedingZhang commented Aug 30, 2026 •

Copy link
Copy Markdown

Description

Nested editor.update() calls on the same editor are queued while that editor is updating, so source order can differ from execution order. This adds @lexical/no-nested-editor-updates as a warning in the default flat presets and an error in the monorepo.

The rule compares receiver expressions and identifier bindings in direct update, registerCommand, and registerNodeTransform callbacks, preserving valid cross-editor updates. Both read overloads receive a separate diagnostic that keeps the update wrapper and moves the update after the read. Dollar-prefixed helpers receive guidance about owning their editor context, with wrapper removal and option migration explicitly conditioned on targeting the active editor. Transform diagnostics link to the preconditions needed for inline mutations to converge. Statically known tag, discrete, and onUpdate options receive guidance using $addUpdateTag, $flushSyncAfterUpdate, and $onUpdate; skipTransforms and opaque option bags remain conservatively ignored. There is no autofix.

Async callbacks and async dollar functions are skipped because an await can end the active editor context. Synchronous editor callbacks nested inside async functions are still checked. Aliases, callbacks passed by reference, and another nested callback layer remain outside the analysis.

The plugin uses ESM sources, named exports, and flat configurations. recommended, all, and their flat/* aliases enable the rule. Both rules use a shared getSourceCode(context) helper that retains the existing ESLint 8 method fallback while using context.sourceCode on modern ESLint. The new rule resolves receiver references through ESLint's scope/reference API, falling back to scopeManager when SourceCode#getScope is unavailable before ESLint 8.37; the existing rules-of-lexical declaration lookup is preserved.

Repository cleanups preserve update options and existing cross-editor history coverage:

  • Find/Replace runs inside the command update and uses $flushSyncAfterUpdate() to preserve synchronous commits.
  • Yjs initialization uses the existing outer update and its HISTORY_MERGE_TAG.
  • Checklist and playground command handlers use their existing update context.
  • Tests intentionally exercising nested-update semantics retain per-site suppressions.
  • Helpers that open their own update lose misleading dollar prefixes.

Closes #7040

Changeset

.changeset/no-nested-editor-updates.md covers the new rule, its conservative async boundary, legacy scope lookup, conditional editor-ownership and transform guidance, and repository behavior changes.

Test plan

Before

The new regressions reproduce the pre-8.37 scope lookup crash and assert the conditional dollar-function and transform guidance:

$ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit
TypeError: sourceCode.getScope is not a function
Test Files  2 failed | 3 passed (5)
Tests  8 failed | 27 passed (35)

After

Validated on eac3d467 with macOS / Node 26:

$ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit
Test Files  5 passed (5)
Tests  35 passed (35)

$ pnpm run ci-check
Changeset check passed: 101 pending changeset(s) valid.
Found 0 errors
(exit 0)

$ pnpm run build
(exit 0)

$ node packages/lexical-eslint-plugin/__tests__/integration/integration-test.mjs
Total tests: 4
Passed: 4

$ git diff --check HEAD^ HEAD
(exit 0)

Additional smoke checks against the built plugin pass on actual ESLint 8.0.0, 8.36.0, 8.37.0, 8.39.0, 8.40.0, 9.39.5, and 10.14.0: 17 cases per version covering resolved, unresolved and shadowed editor bindings, cross-editor updates, transform and dollar-function guidance with options, both read overloads, async contexts, and the existing rule's fixes and suggestions. The cross-version comparison includes diagnostic locations and fix/suggestion payloads, excluding only the nodeType field removed by ESLint 10.

The committed compatibility regressions compare the full diagnostic payloads with and without context.sourceCode, and with and without SourceCode#getScope. They include function- and block-scoped shadowing so the legacy fallback cannot silently change which editor bindings match.

Browser-mode and E2E matrices were not run locally for this ESLint-only follow-up.

@meta-cla

meta-cla Bot commented Aug 30, 2026

Copy link
Copy Markdown

Hi @ZedingZhang!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks!

@vercel

vercel Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
lexical Ready Ready Preview Nov 17, 2026 4:34am UTC
lexical-playground Ready Ready Preview Nov 17, 2026 4:34am UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Aug 30, 2026
@meta-cla

meta-cla Bot commented Aug 30, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label Aug 30, 2026

@etrepum etrepum left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be configured by default at least locally in the repo to make sure it finds the issues we expect it to

@ZedingZhang

ZedingZhang commented Aug 30, 2026 •

Copy link
Copy Markdown
Author

Update: this status was superseded by the review fixes in ff5da9a. The cross-editor history rewrite and file-wide LexicalEditor.test.tsx override described here were reverted; the rule now distinguishes editor bindings and intentional nested-update tests use per-site suppressions. See the complete review response and the updated PR description for the current implementation and validation results.

@etrepum

etrepum commented Aug 30, 2026

Copy link
Copy Markdown
Collaborator
Here is an additional review from claude code

Review

The rule idea is good and the implementation is tidy — extracting getLexicalFunctionName / getFunctionNameIdentifier into a shared util is a nice touch. But there's a design hole that makes the rule emit actively dangerous advice, plus a few behavior changes riding along in the "fix" commits.

What I verified locally

Check Result
npx eslint ./ on PR head clean, 0 problems — the "repo is clean with the rule on" claim holds
Same lint against the pre-PR versions of the 13 touched files 15 errors (the ones this PR fixes)
npx vitest run on lexical-{history,list,clipboard,code-prism,code-shiki,eslint-plugin} 36 files / 409 tests passed
npx tsc --noEmit -p ., npx prettier --check on changed files clean

Blocking

1. The rule can't distinguish "this editor" from "a different editor", and the message tells you to do the wrong thing

updateEditor (packages/lexical/src/LexicalUpdates.ts:1332) only defers when that editor's _updating is set. childEditor.update() inside the parent's update isn't nested at all — it's the canonical nested-editor pattern. The rule flags it anyway:

editor.registerCommand(CMD, () => {
  const nestedEditor = getNestedEditor();
  nestedEditor.update(() => {});   // error: "Remove the nested nestedEditor.update wrapper"
  return true;
}, 0);

export function $syncChild(childEditor: LexicalEditor) {
  childEditor.update(() => {});    // error: "Remove the nested childEditor.update wrapper"
}

Following that message would run the child's mutations against the parent's active context. The false positive is encoded as invalid in the rule's own tests:

editor.registerNodeTransform(Node, node => {
  nestedEditor.update(() => node.remove());
});

The rule should only fire when the receiver is provably the same editor as the enclosing context (same identifier/binding), and treat a differently-named receiver as out of scope.

2. That false positive drove a test rewrite that loses coverage

packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx was the only non-$-named real-world hit in the whole monorepo:

821:9  error  editor.update callback already provides ... Remove the nested child.getOrResetEditor().update wrapper

The original built the child inside the parent's update via getOrResetEditor(), which exercises NestedEditorExtension's $defaultGetParentEditor — that calls $getEditor() and therefore requires the parent update context (packages/lexical-extension/src/NestedEditorExtension.ts:25). The rewrite hoists creation outside the update and passes $getParentEditor: () => parentEditor explicitly, so neither $defaultGetParentEditor nor getOrResetEditor's creation branch is covered any more.

Worth noting: the same file still has editor.read(() => { $getChildEditor().update(..., {discrete: true}) }) untouched — identical pattern, unflagged only because read isn't in implicitUpdateCallbackIndex.

3. {discrete: true} silently dropped

packages/lexical-playground/src/plugins/FindReplaceExtension/index.tsx, both REPLACE_CURRENT_COMMAND and REPLACE_ALL_COMMAND. $processNestedUpdates sets pendingEditorState._flushSync = true for a discrete nested update (LexicalUpdates.ts:1092), forcing a synchronous commit; without it the commit goes through scheduleMicroTask (LexicalUpdates.ts:1277). Replace now commits asynchronously, and nothing tests it either way. Either preserve discreteness or note in the description why the deferral is fine.


Should fix

4. Wrong message for the $-naming class

5 of the 15 findings were $pasteHtml / $insertOverFirstParagraph / $runOutdentScenario — helpers whose real defect is the $ prefix on a function that opens its own update. The message says "Remove the nested editor.update wrapper"; the fix actually applied was a rename. A second messageId would help, e.g. "{{name}} opens its own editor context — drop the $ prefix or remove the wrapper".

5. Consumer-visible changes in published packages, unmentioned and untested

@lexical/react useYjsCollaboration (a user-supplied initialEditorState function now runs inline instead of in a deferred nested update) and @lexical/list checkList. Reading $beginUpdate, both look equivalent — nested updates flush at LexicalUpdates.ts:1186, before transforms, in the same commit — but AGENTS.md's backwards-compat section argues for calling these out explicitly, ideally in a commit separate from the lint rule.

6. Copy-paste duplication with rules-of-lexical.js

parseMatcherOption, getSourceCode, matcherSchema, and the isDollarFunction: [/^\$[a-z_]/] default are verbatim copies. This PR already created a util module for the shared parts — these belong there too, so the $ heuristic can't drift between the two rules.

7. configs['flat/all'] doesn't include the new rule

no-document-in-dom-methods is already missing from it, so "all" keeps getting less true. Add it, or document what "all" is meant to cover.


Nits / follow-ups

  • Not caught, and arguably higher-value than what is: editor.read(() => editor.update(...)). AGENTS.md says outright "Do NOT nest updates in reads." Verified not reported.
  • Not caught: one closure deep — editor.update(() => arr.forEach(() => editor.update(...))). Exempting setTimeout is right and structurally indistinguishable from forEach, so probably just a documented limitation.
  • Not caught: a handler passed by reference, editor.registerCommand(CMD, handleThing, 0). Same — worth a "Known limitations" section in the README.
  • eslint.config.mjs turns the rule off for all of LexicalEditor.test.tsx; per-site eslint-disable-next-line would keep the rest of that large file covered.
  • The new eslint.config.mjs block has no files key so it applies to every linted file. Matches flat/all's own shape, so likely intentional.
  • LayoutExtension's return; → return true; in UPDATE_LAYOUT_COMMAND is correct (the handler returned true on that path before too) — flagging only because it's the one spot in the diff that changes a return statement.

@ZedingZhang

Copy link
Copy Markdown
Author

Addressed the additional review in ff5da9a and rebased the branch onto the current main.

  • The rule now reports callback cases only when the inner receiver resolves to the same identifier binding as the enclosing editor. Differently named receivers and child.getOrResetEditor() are out of scope, with explicit valid tests for the cross-editor patterns from the review.
  • Restored the shared-history test unchanged, including the default NestedEditorExtension parent lookup and getOrResetEditor() creation branch.
  • Restored both Find/Replace {discrete: true} updates and added per-call lint suppressions explaining the synchronous flush requirement.
  • Added a separate $-function diagnostic that suggests either dropping the $ prefix or removing the wrapper.
  • Preserved the Yjs secondary emptiness check and now uses $addUpdateTag(HISTORY_MERGE_TAG) in the existing update. The PR description now calls out the published-package cleanups; a focused checklist space-key test was added, and the collaboration bootstrap/undo coverage passes.
  • Moved parseMatcherOption, getSourceCode, matcherSchema, the default $ matcher, and identifier-binding lookup into shared utilities used by both rules.
  • Documented the historical compatibility meaning of the all presets (they currently enable only rules-of-lexical; other exported rules remain opt-in).
  • Added same-editor read callback detection, documented the one-closure and by-reference-handler limitations, and replaced the file-wide LexicalEditor.test.tsx override with per-site suppressions.

Validation on the rebased head: full lint, TypeScript, build, Prettier on changed files, all 6 ESLint 8/10 integration scenarios, 7 affected suites, and the full core unit project (311 files / 4,746 passed / 1 skipped).

@etrepum etrepum left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's fine to go ahead and make new rules opt-out, so long as the rules don't have a lot of false positives. Most of the value is in having defaults is to prevent as many errors as possible, not to be as backwards compatible as possible. Anyone that wants a configuration that's frozen in time shouldn't be using defaults.

That said, I don't think we're quite there yet with this.

Claude review

Reviewed at ff5da9a against merge base 1723cd1.

Verification: tsc -p . clean · eslint . clean · plugin unit tests 21/21 · lexical + lexical-react unit 1147/1147 (2 browser-mode files unrun locally — no Playwright browser) · lexical-list / lexical-clipboard / lexical-code-* 361/361.

The rule targets a real hazard — updateEditor pushes to editor._updates when editor._updating (LexicalUpdates.ts:1332), so source order really does diverge from execution order — and the identifier-binding comparison added in ff5da9a is the right shape. Four issues below are worth fixing before merge.


1. The read diagnostic gives advice that throws

editor.read is in implicitUpdateCallbackIndex, so this is reported:

editor.read(() => {
  editor.update(() => {});
});
// editor.read callback already provides an update context for this editor.
// Remove the nested editor.update wrapper.

A read callback is a read-only context, not an update context, and the nested update is the only thing that makes the write land. Following the message:

Error: Cannot use method in read-only mode.
 ❯ errorOnReadOnly packages/lexical/src/LexicalUpdates.ts:106:5
 ❯ $createParagraphNode packages/lexical/src/nodes/LexicalParagraphNode.ts:218:32
 ❯ EditorState.read packages/lexical/src/LexicalEditorState.ts:166:12

The PR already suppresses exactly this twice in LexicalEditor.test.tsx ("Nesting update in read works, although it is discouraged"). read needs its own messageId — something like "an update nested in read() is deferred until the read returns; move it after the read" — or should be dropped from the map. The README inherits the error: "This includes the callbacks passed to editor.update, editor.read, … already inside an update context".

Related false negative: read has a two-arg overload (read(mode, fn), LexicalEditor.ts:1848). The hardcoded callback index 0 misses editor.read('latest', () => editor.update(...)) — verified unreported.

2. Nested updates carrying options get "just remove the wrapper"

Verified against the rule:

editor.update(() => { editor.update(() => {}, {discrete: true}); });
// -> editor.update callback already provides an update context for this editor.
//    Remove the nested editor.update wrapper.

editor.registerCommand(C, () => { editor.update(() => {}, {tag: 'history-merge'}); }, 1);
// -> same message

Removing the wrapper silently drops discrete, tag, onUpdate, and skipTransforms. The PR itself hits this three times — two eslint-disables in FindReplaceExtension for {discrete: true}, and a hand-conversion to $addUpdateTag in useYjsCollaboration.

Suggestion: when node.arguments.length > 1, either skip the report or use a message that names the options and their in-context equivalents ($addUpdateTag, $onUpdate). {discrete: true} in particular is almost always deliberate and is a good candidate for a default exemption.

3. A $-named callback silences the same-editor check

getImplicitUpdateContext returns the dollarFunction context and never falls through to the editor-callback branch. Since isCurrentEditorInDollarFunction only accepts the literal names editor / $getEditor, any other editor variable escapes entirely:

// REPORTED
childEditor.update(() => { childEditor.update(() => {}); });

// NOT reported — the $ name shadows the editorCallback check
childEditor.update(function $inner() { childEditor.update(() => {}); });

// NOT reported
const $h = useCallback(() => { childEditor.update(() => {}); }, []);
childEditor.registerCommand(C, $h, 1);

$-prefixed callbacks are idiomatic here ($onEscape in ImageComponent.tsx is one), so this hole is easy to hit in practice. When the dollarFunction check doesn't fire, fall through to the editorCallback check rather than returning early.

4. The new checkList test doesn't cover the change it justifies

packages/lexical-list/src/checkList.ts drops an editor.update() wrapper — a behavior change in a shipped package. Checking out the base checkList.ts and running the new test against it:

 Test Files  1 passed (1)
      Tests  7 passed (7)

It passes both ways, because $beginUpdate drains editor._updates synchronously before the DOM event handler returns, so event.preventDefault() was already in time. Either drop the test or reshape it to assert the ordering that actually changed.


Smaller items

  • useYjsCollaboration.tsx — the outer editor.update in initializeEditor already passes {tag: HISTORY_MERGE_TAG}, so the added $addUpdateTag(HISTORY_MERGE_TAG) and its import are dead. And root1.isEmpty() is now provably always true: it sits inside if (root.isEmpty()) with no intervening mutation. That re-check existed because the update was deferred; inlining makes it a dead guard. Existing collab tests (the bootstrapped initialEditorState can not be undone) do cover the callback path and pass, so this is cleanup rather than a correctness risk — but the guard removal should be deliberate, not incidental.
  • Commit subject — [lexical-eslint-plugin] Feature: …, but the diff also changes lexical-list and lexical-react (shipped behavior) plus playground and examples. AGENTS.md requires the subject to name every packages/ directory the diff touches.
  • isSameEditorExpression hardcodes '$getEditor' in the zero-arg-call branch, so a user-configured accessor (isEditor: '^getMyEditor$') is recognized by getEditorMethod but can never match as "same editor" — silently inconsistent with what the isEditor option advertises.
  • this.editor.update(() => this.editor.update(...)) is unreported — isSameEditorExpression has no ThisExpression case. Cheap to add.
  • getIdentifierVariable rewrite now scans every scope and every variable in scopeManager and resolves via variable.references, replacing the old parent-walk plus scope.set name fallback. That is a semantic change to rules-of-lexical, not just a move: it resolves arbitrarily deep references the old version missed, and drops the name-based fallback. It reads as neutral-to-better and the existing rule tests pass, but it deserves a line in the description since it wasn't advertised as a behavior change. Both callers are gated (reportedSet in rules-of-lexical, candidate sites in the new rule), so the O(scopes × variables) scan isn't a practical concern.
  • ImageComponent.tsx is fine as rewritten: setSelected itself calls editor.update (useLexicalNodeSelection.ts:86), so the observable order ($setSelection(null) → focus() → selection update) is unchanged.

Items 1–3 are rule bugs that will mislead adopters; 4 is a test that doesn't test. The rest are cleanups.

@ZedingZhang
ZedingZhang force-pushed the feature/no-nested-editor-updates branch from ff5da9a to 53a06de Compare August 31, 2026 06:01
@ZedingZhang ZedingZhang changed the title [lexical-eslint-plugin] Feature: flag accidental nested editor updates [lexical][lexical-clipboard][lexical-code-core][lexical-code-prism][lexical-code-shiki][lexical-eslint-plugin][lexical-list][lexical-playground][lexical-react] Feature: flag accidental nested editor updates Aug 31, 2026
@ZedingZhang

ZedingZhang commented Aug 31, 2026 •

Copy link
Copy Markdown
Author

Follow-up (26ffff827): The “Update options” item below is superseded by the later review response. Statically analyzable tag, discrete, and onUpdate options are now reported with their in-context helpers; only skipTransforms and option bags that may conceal it remain exempt. Find/Replace now uses $flushSyncAfterUpdate() directly in the command context.


Addressed the latest review in 53a06debd and rebased the branch onto current main (d75ee5627).

  1. Read diagnostics: read() now has its own readOnlyUpdate message. It explains that the nested update is deferred and should be moved after the read callback; it never suggests removing the wrapper. Callback detection covers both read(callback) and read(mode, callback), and the README now describes reads as read-only rather than as update contexts. A $-named read callback also receives the read-specific message.
  2. Update options: calls with more than one argument are exempt. This avoids unsafe advice for discrete, tag, onUpdate, and skipTransforms. The Find/Replace {discrete: true} calls are unchanged and their now-unnecessary lint suppressions were removed. Option-bearing core tests likewise no longer need suppressions.
  3. $-named callbacks: direct editor callback ownership is checked before dollar-function ownership. childEditor.update(function $inner() { childEditor.update(...) }) is now reported as a same-editor nested update. The documented local-analysis boundary remains for callbacks passed by reference.
  4. Checklist test: removed the space-key test because it did not distinguish the old and new implementations.

The smaller items are also addressed:

  • Removed the redundant Yjs $addUpdateTag import/call and the dead second root.isEmpty() check. The existing outer update already carries HISTORY_MERGE_TAG.
  • Enabled no-nested-editor-updates as a warning in the default legacy and flat presets and marked it recommended; the monorepo still promotes it to an error.
  • Configured zero-argument editor accessors such as getMyEditor() now participate in same-expression matching instead of being hardcoded to $getEditor().
  • Added this.editor matching across arrow callbacks while deliberately not equating this across ordinary function callbacks.
  • Documented the getIdentifierVariable scope-resolution behavior change in the PR description and in the relevant commit description.
  • Rewrote all commit messages to the repository template, including every affected packages/ directory in each subject, and updated the PR title to match the full package scope. Compared with ff5da9a19, the patch intentionally drops the non-discriminating checklist test and the now-unnecessary Find/Replace suppressions while adding the rule fixes above. After those code fixes were committed as 8b322c21b, the later message-only rewrite to 53a06debd preserved the tree byte-for-byte.

Validation on the rebased head:

  • focused rule and affected behavior suites: 7 files / 191 tests passed;
  • full core unit project: 312 files / 4,776 passed / 1 skipped;
  • ESLint 8 legacy/deprecated and ESLint 10 flat fixtures: 6/6 passed;
  • full lint, TypeScript, build, and Prettier checks passed.

Browser-mode and E2E suites were not run locally; the refreshed GitHub Actions matrix is starting on the new head.

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good. The rule targets a real hazard: a same-editor update() inside an update, command or transform callback is queued, so source order and execution order differ. The diagnostics now handle the cases raised in earlier review rounds: cross-editor receivers, both read() overloads, $-named callbacks, update options and this.editor. The repository rewrites keep their behavior (Find/Replace stays synchronous through $flushSyncAfterUpdate(), and the Yjs bootstrap keeps its empty-root guard and HISTORY_MERGE_TAG). All of the suggestions below are optional and non-blocking, except that the first will be needed before this can merge cleanly.

  1. Rebase onto current main and add two suppressions (eslint.config.mjs:351). Since this branch's merge base, #9219 added two intentional nested updates to packages/lexical/src/__tests__/unit/LexicalSelectionChangeCommand.test.ts, at lines 123 and 351 on main. With the rule at ERROR in the monorepo, lint on the merged tree reports both as errors. CONTRIBUTING.md asks that the code lints. Per-site // eslint-disable-next-line @lexical/no-nested-editor-updates -- … comments, like the ones in LexicalEditor.test.tsx, would fix it.
  2. Fix the readOnlyUpdate timing claim (packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:496). The message says the nested update "is deferred until the read returns". Outside an update, updateEditor runs the update immediately because editor._updating is false: the callback runs inside the read and only its commit waits. Inside an update, the call waits until the enclosing update's callback ends. The advice is right; only the explanation needs changing. For example: "{{context}} is read-only and cannot observe {{callee}}; move the update after the read callback instead of removing its wrapper."
  3. Mention convergence for transforms (packages/lexical-eslint-plugin/README.md, "Preventing nested editor updates"). Today, an update queued from a transform runs after the transform pass, so its edits are not transformed. Without the wrapper, those edits are transformed again, and a mutation without a precondition will loop until Lexical's infinite-transform guard throws. One sentence pointing at the preconditions section of docs/concepts/transforms.md would cover it.
  4. Nit: which receivers count as the active editor (packages/lexical-eslint-plugin/README.md:106-107, :124). Inside $functions, configured isEditor patterns also count as the active editor, not only editor and $getEditor(). The default /editor$/i already matches zero-argument calls such as getNestedEditor(), not only configured accessors.

Enabling the rule in the default presets follows the direction a maintainer gave earlier in this thread for rules with few false positives. Across packages/, examples/ and dev-examples/, every report I saw was a genuine same-editor or $-function nesting. The CI workflows for this head still need maintainer approval to run.

Comment thread eslint.config.mjs Resolved
ZedingZhang and others added 8 commits November 6, 2026 04:03
## Description

Nested same-editor updates can run in a different order depending on whether their caller already has an active Lexical context. This makes command handlers and dollar functions difficult to reason about and can hide ordering bugs.

Add the @lexical/no-nested-editor-updates rule, its public options type, RuleTester coverage, and consumer documentation. The rule recognizes direct callbacks that provide an update context and dollar functions that open their own update, while avoiding unrelated update methods. Extract the shared Lexical function-name helpers so both plugin rules use the same naming logic.

The rule reports without autofixing because the safe rewrite depends on the call site.

Closes meta#7040

## Test plan

### Before

```text
RuleTester nested-update fixture

AssertionError: Should have 1 error but had 0: []
```

### After

```text
corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts --run

Test Files  1 passed (1)
Tests       3 passed (3)
```

```text
corepack pnpm tsc
corepack pnpm exec prettier --check packages/lexical-eslint-plugin

Both commands exited successfully.
```

Browser-mode and E2E suites were not run locally because this commit changes only the ESLint plugin.
…de-shiki][lexical-history][lexical-list][lexical-playground][lexical-react] Chore: enable nested update lint locally

## Description

Enable @lexical/no-nested-editor-updates as an error in the monorepo so new accidental nesting is caught during normal lint runs.

Resolve the existing findings by removing redundant same-editor wrappers from callbacks that already have a Lexical context and by renaming helpers whose dollar prefix incorrectly promised that callers supplied one. Keep behavior-specific updates explicit where their call sites require separate timing or context.

Closes meta#7040

## Test plan

### Before

```text
corepack pnpm lint

✖ 15 problems (15 errors, 0 warnings)
```

### After

```text
corepack pnpm lint

0 problems
```

```text
corepack pnpm vitest packages/lexical-history packages/lexical-list packages/lexical-clipboard packages/lexical-code-prism packages/lexical-code-shiki --run

Test Files  36 passed (36)
Tests       409 passed (409)
```

```text
corepack pnpm tsc
corepack pnpm build

Both commands exited successfully.
```

Browser-mode and E2E suites were not run locally; the pull request CI matrix covers them.
…al-playground][lexical-react] Bug Fix: avoid cross-editor false positives

## Description

The initial rule treated updates to child editors as though they were nested updates on the active parent editor. Its generic diagnostic could therefore recommend a behavior-changing rewrite.

Compare editor identifier bindings before reporting callback cases, preserve cross-editor history coverage and intentional discrete updates, and use separate guidance for dollar-function ownership. Add read callback detection, document the rule's local-analysis limits, share matcher and scope helpers with rules-of-lexical, and replace broad test-file exclusions with per-site suppressions.

The shared identifier lookup now resolves references across the scope manager instead of relying on a parent-scope name fallback, which lets both rules distinguish shadowed bindings more consistently.

Closes meta#7040

## Test plan

### Before

```text
RuleTester cross-editor fixture

AssertionError: Should have no errors but had 1
```

### After

```text
corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts packages/lexical-eslint-plugin/src/__tests__/unit/rules-of-lexical.test.ts packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx packages/lexical-list/src/__tests__/unit/checkList.test.tsx packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx --run

Test Files  7 passed (7)
```

```text
corepack pnpm vitest --project unit --no-watch

Test Files  311 passed (311)
Tests       4746 passed | 1 skipped (4747)
```

```text
corepack pnpm test-eslint-integration

Total tests: 6
Passed: 6
```

```text
corepack pnpm lint
corepack pnpm tsc
corepack pnpm build
corepack pnpm exec prettier --check <changed files>

All commands exited successfully.
```

Browser-mode and E2E suites were not run locally; the pull request CI matrix covers them.
…xical-react] Bug Fix: make nested update diagnostics safe

## Description

Nested updates in read callbacks and updates carrying options received advice to remove a wrapper even when doing so would throw or discard behavior. Dollar-prefixed callback names could also hide the stronger same-editor callback check.

Give read callbacks a read-only diagnostic that recommends moving the update, recognize both read overloads, and exempt calls with update options. Check direct editor callback ownership before dollar-function ownership, support configured zero-argument editor accessors, and compare this.editor across lexical arrow callbacks.

Enable the rule as a warning in the default presets after reducing false positives. Remove obsolete suppressions, drop the checklist test that passed against both implementations, and remove the redundant Yjs bootstrap guard and tag operation identified in review.

Closes meta#7040

## Test plan

### Before

```text
corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts --run

Test Files  1 failed (1)
Tests       3 failed | 1 passed (4)
AssertionError: Should have no errors but had 4
AssertionError: Should have 1 error but had 0
```

### After

```text
corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts --run

Test Files  1 passed (1)
Tests       4 passed (4)
```

```text
corepack pnpm vitest packages/lexical-eslint-plugin/src/__tests__/unit/no-nested-editor-updates.test.ts packages/lexical-eslint-plugin/src/__tests__/unit/rules-of-lexical.test.ts packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx packages/lexical-list/src/__tests__/unit/checkList.test.tsx packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx --run

Test Files  7 passed (7)
Tests       191 passed (191)
```

```text
corepack pnpm vitest --project unit --no-watch

Test Files  312 passed (312)
Tests       4776 passed | 1 skipped (4777)
```

```text
corepack pnpm test-eslint-integration

Total tests: 6
Passed: 6
```

```text
corepack pnpm lint
corepack pnpm tsc
corepack pnpm build
corepack pnpm exec prettier --check <changed files>

All commands exited successfully.
```

Browser-mode and E2E suites were not run locally; the pull request CI matrix covers them.
…e nested update options in context

## Description

The nested update rule skipped every call with an options argument, even though `tag`, `discrete`, and `onUpdate` can be applied to the active update context. This left actionable nested updates unreported and kept two nested `editor.update(..., {discrete: true})` calls in Find/Replace.

Report statically analyzable option objects when every option has an in-context helper, and name `$addUpdateTag`, `$flushSyncAfterUpdate`, or `$onUpdate` in the diagnostic. Continue to skip `skipTransforms` and opaque option bags because they cannot be migrated safely. Move Find/Replace command mutations into their existing command update and preserve synchronous commits with `$flushSyncAfterUpdate()`. Keep explicit lint suppressions only in core tests whose purpose is to exercise nested update behavior.

Closes meta#7040

## Test plan

### Before

With the two `$flushSyncAfterUpdate()` calls temporarily removed:

```text
$ corepack pnpm vitest --project unit --no-watch packages/lexical-playground/__tests__/unit/FindReplace.test.ts -t synchronously

❯ FindReplace.test.ts (55 tests | 2 failed | 53 skipped)
× REPLACE_CURRENT_COMMAND replaces the current match synchronously
Expected: "baz bar foo"
Received: "foo bar foo"
× REPLACE_ALL_COMMAND replaces all matches synchronously
Expected: "qux bar qux"
Received: "foo bar foo"

Test Files  1 failed (1)
Tests       2 failed | 53 skipped (55)
```

### After

```text
$ corepack pnpm vitest --project unit --no-watch packages/lexical-eslint-plugin/src/__tests__/unit packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx
Test Files  6 passed (6)
Tests       168 passed (168)

$ corepack pnpm test-eslint-integration
Total tests: 6
Passed: 6
✓ All tests passed!

$ corepack pnpm lint
> eslint ./
(exit 0)

$ corepack pnpm tsc
> tsc
(exit 0)

$ corepack pnpm build
> node scripts/build.mjs
(exit 0)

$ corepack pnpm exec prettier --check <changed files>
Checking formatting...
All matched files use Prettier code style!
```

Browser-mode and E2E suites were not rerun locally; GitHub Actions will exercise those matrices on the pushed head.
…g Fix: adapt nested update lint to ESM

## Description

The nested-update rule and its shared utilities still used CommonJS after the plugin sources moved to ESM in meta#9127. Export those modules as ESM, verify the rule through both the default plugin and its module namespace, and check the current flat presets and their aliases instead of the removed legacy preset.

Update the configuration documentation and rename three newly added upstream test helpers that open their own editor updates, preserving their discrete updates and history tags.

## Test plan

### Before

```text
$ node -e "import('./packages/lexical-eslint-plugin/src/LexicalEslintPlugin.js')"
SyntaxError: The requested module '../util/ruleOptions.js' does not provide an export named 'DEFAULT_DOLLAR_FUNCTION_MATCHER'

$ node node_modules/vitest/vitest.mjs run --project unit packages/lexical-eslint-plugin/src/__tests__/unit
TypeError: Cannot read properties of undefined (reading 'rules')
Test Files  1 failed | 3 passed (4)
Tests  1 failed | 19 passed (20)
```

After rebasing onto the latest main, the newly added table test helper also failed the enabled rule:

```text
$ corepack pnpm lint

packages/lexical-table/src/__tests__/unit/TableFieldAccessors.test.ts
  74:3  error  $withEditor is named as a Lexical $function but calls editor.update  @lexical/no-nested-editor-updates

✖ 1 problem (1 error, 0 warnings)
```

### After

```text
$ corepack pnpm vitest --project unit --no-watch packages/lexical-eslint-plugin/src/__tests__/unit packages/lexical-clipboard/src/__tests__/unit/ClipboardImportExtension.test.ts packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx packages/lexical-list/src/__tests__/unit/checkList.test.tsx packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx packages/lexical-extension/src/__tests__/unit/HMRExtension.test.ts packages/lexical-table/src/__tests__/unit/TableFieldAccessors.test.ts packages/lexical/src/__tests__/unit/Issue4815Repro.test.ts

Test Files  13 passed (13)
Tests       283 passed (283)
```

```text
$ corepack pnpm lint
$ corepack pnpm tsc
$ corepack pnpm tsc-scripts
$ corepack pnpm tsc-extension
$ corepack pnpm tsc-website
$ corepack pnpm prettier
$ corepack pnpm build

All commands exited successfully.
```

The ESLint integration script could not be rerun on native Windows because it launches `/bin/bash`; the refreshed GitHub Actions workflow covers it. Browser-mode and E2E suites were not run locally and are also covered by the pull request CI matrix.
…ation

## Description

Keep rules-of-lexical's original declaration lookup and resolve editor receiver references only in no-nested-editor-updates. Remove the shared whole-scope scanner, duplicated diagnostic construction, and the SourceCode fallback for ESLint 8, which is outside the declared peer range. Shorten repeated README examples while retaining the supported patterns and analysis limits.

The existing diagnostics, presets, repository activation, migration changes, and regression tests are preserved. Individual migration reversions and a missing-flush mutation established which changes must remain.

## Test plan

### Before

Ablation control: temporarily reusing the original declaration lookup for receiver references misses six of fourteen probe cases. The existing plugin tests also detect the regression:

```text
$ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit
Test Files  1 failed | 3 passed (4)
Tests  2 failed | 18 passed (20)
```

### After

```text
$ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit packages/lexical-playground/__tests__/unit/FindReplace.test.ts packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx packages/lexical-list/src/__tests__/unit/checkList.test.tsx packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx packages/lexical-extension/src/__tests__/unit/HMRExtension.test.ts packages/lexical/src/__tests__/unit/Issue4815Repro.test.ts packages/lexical-code-prism/src/__tests__/unit/LexicalCodeNodeTabs.test.ts packages/lexical-code-shiki/src/__tests__/unit/LexicalCodeNodeTabs.test.ts packages/lexical-clipboard/src/__tests__/unit/ClipboardImportExtension.test.ts packages/lexical-table/src/__tests__/unit/TableFieldAccessors.test.ts
Test Files  15 passed (15)
Tests  451 passed (451)

$ pnpm exec npm-run-all --parallel tsc tsc-scripts tsc-extension tsc-website prettier lint
(exit 0)

$ node node_modules/flow-bin/cli.js full-check --max-workers 4
Found 0 errors

$ pnpm run build
(exit 0)

$ git diff --check
(exit 0)
```

The new rule's diagnostics match the original PR head in 798 JavaScript/TypeScript cases; twelve existing-rule cases match the merge base, including fix/suggestion payloads. Published-build smoke checks pass for ESLint 9 and 10: the original valid/invalid fixtures and an additional nested-update fixture, six scenarios total.

On Windows/Node 24, the unchanged ci-check Flow launcher fails with spawn EINVAL when spawning flow.cmd. The checks above run its static-check commands directly and invoke the native Flow CLI. Browser and E2E matrices were not run.
…x: finish nested-update review follow-ups

## Description

After rebasing onto main at dfe058a, the repository-wide nested-update rule reports nine findings in newly added code. Add per-site exemptions for tests of nested update ordering and error recovery, and for the collaboration self-check's separate verification editor. Rename the block-container test helpers that own their update context or only manipulate strings.

Make the read-only diagnostic describe the required move while preserving the update wrapper and options. Document transform convergence and the configured editor matchers and default zero-argument accessors. Add the changeset required by the current repository guidelines for this PR.

## Test plan

### Before

```text
$ pnpm run lint
✖ 9 problems (9 errors, 0 warnings)
[ELIFECYCLE] Command failed with exit code 1.
```

```text
$ pnpm run check-changesets -- --base upstream/main
Changeset check found 1 problem(s):
- This pull request changes published code without a changeset for:
    @lexical/eslint-plugin
    @lexical/list
    @lexical/react
```

### After

```text
$ pnpm run ci-check
Changeset check passed: 101 pending changeset(s) valid.
Found 0 errors
(exit 0)

$ pnpm run build
(exit 0)

$ pnpm run test-eslint-integration
Total tests: 4
Passed: 4
```

```sh
pnpm exec vitest run --project unit --maxWorkers=4 \
  packages/lexical-eslint-plugin/src/__tests__/unit \
  packages/lexical-playground/__tests__/unit/FindReplace.test.ts \
  packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx \
  packages/lexical/src/__tests__/unit/LexicalSelectionChangeCommand.test.ts \
  packages/lexical/src/__tests__/unit/LexicalUpdateErrors.test.ts \
  packages/lexical-history/src/__tests__/unit/LexicalHistory.test.tsx \
  packages/lexical-list/src/__tests__/unit/checkList.test.tsx \
  packages/lexical-react/src/__tests__/unit/LexicalCollaborationPlugin.test.tsx \
  packages/lexical-extension/src/__tests__/unit/HMRExtension.test.ts \
  packages/lexical-extension/src/__tests__/unit/BlockContainers.test.ts \
  packages/lexical/src/__tests__/unit/Issue4815Repro.test.ts \
  packages/lexical-code-prism/src/__tests__/unit/LexicalCodeNodeTabs.test.ts \
  packages/lexical-code-shiki/src/__tests__/unit/LexicalCodeNodeTabs.test.ts \
  packages/lexical-clipboard/src/__tests__/unit/ClipboardImportExtension.test.ts \
  packages/lexical-table/src/__tests__/unit/TableFieldAccessors.test.ts \
  packages/lexical-y/src/__tests__/unit/regressions/RemoteReadAppEdits.test.ts \
  packages/lexical-y/src/__tests__/unit/SelfCheckBuilder.test.ts \
  packages/lexical-y/src/__tests__/unit/FollowUpTextFields.test.ts \
  packages/lexical-y/src/__tests__/unit/regressions/FollowUps.test.ts
```

```text
Test Files  22 passed (22)
Tests  1030 passed | 1 expected fail (1031)
```

The expected-failure case uses test.fails in FollowUps.test.ts. Additional published-plugin probes pass on ESLint 9 and 10 for cross-editor updates, same-editor nesting, and the exact read-only diagnostic with update options (three probes per major).

Browser-mode and E2E validation is pending CI.
@ZedingZhang
ZedingZhang force-pushed the feature/no-nested-editor-updates branch from 977e24b to f9abf67 Compare November 5, 2026 20:11
@ZedingZhang ZedingZhang changed the title [lexical][lexical-clipboard][lexical-code-core][lexical-code-prism][lexical-code-shiki][lexical-eslint-plugin][lexical-extension][lexical-list][lexical-playground][lexical-react][lexical-table] Feature: flag accidental nested editor updates [lexical][lexical-clipboard][lexical-code-core][lexical-code-prism][lexical-code-shiki][lexical-eslint-plugin][lexical-extension][lexical-list][lexical-playground][lexical-react][lexical-table][lexical-y] Feature: flag accidental nested editor updates Nov 5, 2026

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working through all the review rounds. The rule's diagnostics now match how Lexical queues same-editor updates, and the repository rewrites (checklist Space handler, Yjs initial state, Find/Replace with $flushSyncAfterUpdate(), playground commands) keep their behavior. The earlier notes on the read-only message, the LexicalSelectionChangeCommand.test.ts suppressions and the README's isEditor wording are all addressed.

Needs a change

  • packages/lexical-eslint-plugin/src/rules/rules-of-lexical.js:189: this PR deletes the getSourceCode(context) helper that main keeps with the comment “kept for ESLint 8 compat”, and reads context.sourceCode directly. ESLint 8 releases before 8.40 have no context.sourceCode, so rules-of-lexical now throws Cannot read properties of undefined (reading 'scopeManager') on its first report instead of warning: under ESLint 8.39 the base rule reports normally and the head rule throws; under 8.40 both work. The new rule doesn't need this cleanup, and the backwards-compatibility section of AGENTS.md asks to keep existing behavior intact when in doubt. Please keep the fallback, for example by exporting a getSourceCode helper from util/ruleOptions.js next to parseMatcherOption and using it in both rules.

Optional, non-blocking

  • packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:419: the rule doesn't look at async, so an async command listener or transform that awaits and then calls editor.update(...) is told to remove the wrapper, although code after an await has already left the outer update. Returning early when the enclosing function is async would avoid that advice.

…ip async update contexts

## Description

Restore the shared getSourceCode(context) fallback used by both rules so ESLint 8.39 reports diagnostics instead of throwing. Keep the modern sourceCode path for ESLint 9 and 10, and preserve fix and suggestion payloads in a regression test.

Skip async enclosing functions in no-nested-editor-updates because an await can end the active editor context. Continue checking synchronous editor callbacks nested inside async functions. Cover command listeners, transforms, both read overloads, update callbacks and dollar functions, and document the conservative boundary.

## Test plan

### Before

With the new regression tests on the previous implementation:

```text
$ pnpm exec vitest run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit
TypeError: Cannot read properties of undefined (reading 'scopeManager')
TypeError: Cannot read properties of undefined (reading 'getScope')
Test Files  2 failed | 3 passed (5)
Tests  3 failed | 20 passed (23)
```

Real ESLint 8.39.0, 8.40.0, 9.39.5 and 10.14.0 smoke cases covering diagnostics, fixes, valid functions and async/sync update boundaries:

```text
$ node ../eslint-compat/smoke.mjs
10 passed, 10 failed
```

### After

```text
$ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit
Test Files  5 passed (5)
Tests  23 passed (23)

$ pnpm run ci-check
Changeset check passed: 101 pending changeset(s) valid.
Found 0 errors
(exit 0)

$ pnpm run build
(exit 0)

$ node packages/lexical-eslint-plugin/__tests__/integration/integration-test.mjs
Total tests: 4
Passed: 4

$ node ../eslint-compat/smoke.mjs "$PWD/packages/lexical-eslint-plugin/dist/LexicalEslintPlugin.js"
20 passed, 0 failed

$ git diff --check
(exit 0)
```

Validated on macOS / Node 26. Browser-mode and E2E matrices were not run for this ESLint-only follow-up.

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. Restoring getSourceCode() as a shared helper fixes the ESLint 8 regression from the last round. Async callbacks are now skipped, and the LexicalSelectionChangeCommand.test.ts suppressions and the README's isEditor wording are in. The rewrites in @lexical/list, @lexical/react and the playground keep their update tags and commit timing. The updated Find/Replace tests fail if $flushSyncAfterUpdate() is removed, so they really guard the synchronous commit.

The GitHub workflows for this head are still waiting for approval, so CI hasn't run yet.

Optional, non-blocking

  • packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:213: SourceCode#getScope() only exists from ESLint 8.37. On 8.0–8.36, the rule throws sourceCode.getScope is not a function for editor.update(() => { editor.update(() => {}); }), even with the restored getSourceCode() fallback. On 8.37 it reports normally. eslint >=9 is the declared peer range, so this doesn't block. But the changeset says both rules keep the ESLint 8 fallback, and AGENTS.md's backwards-compatibility section asks to assume people rely on current behavior. Either resolve the reference through sourceCode.scopeManager when getScope is missing, as getIdentifierVariable in rules-of-lexical.js does, or scope that changeset sentence to ESLint 8.37+.
  • packages/lexical-eslint-plugin/src/__tests__/unit/sourceCodeCompatibility.test.ts:42: the fake legacy context returns ESLint 10's SourceCode, which already has getScope(), so this test can't catch the case above. Removing getScope from the returned object as well would cover it.
  • packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:490: inside a $function, any receiver named editor is taken to be the active editor. That is why $followUpDifference in packages/lexical-y/src/internal/SelfCheck.ts needed a suppression: its local editor is a separate verification editor, so "remove the update wrapper" would be wrong there. Conditioning the whole message, say "If {{callee}} targets the editor this $function runs in, remove the update wrapper, or remove the $ prefix if this function intentionally starts the update", would keep the advice safe when the heuristic misfires.
  • Nit: for registerNodeTransform, the README's note that inline mutations re-enter the transform cycle isn't in the diagnostic itself. A transform-specific message could point to the preconditions docs.

…rify nested update advice

## Description

The nested-update rule throws on ESLint 8.0-8.36 because those SourceCode
objects have no getScope method. Resolve identifier references through
scopeManager when the method is absent, preserving binding identity for
shadowed editor variables. The compatibility regressions now exercise both
legacy SourceCode shapes and compare diagnostics, fixes and suggestions.

Condition both $function diagnostics on the receiver targeting the active
editor before recommending wrapper removal or option migration. Give node
transforms separate diagnostics that link to convergence preconditions,
including when an update has options.

## Changeset

Updated .changeset/no-nested-editor-updates.md with the scope-manager
fallback and the conditional ownership and transform guidance.

## Test plan

### Before

New regressions against the previous implementation:

```text
$ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit
TypeError: sourceCode.getScope is not a function
Test Files  2 failed | 3 passed (5)
Tests  8 failed | 27 passed (35)
```

### After

```text
$ node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=4 packages/lexical-eslint-plugin/src/__tests__/unit
Test Files  5 passed (5)
Tests  35 passed (35)

$ pnpm run ci-check
Changeset check passed: 101 pending changeset(s) valid.
Found 0 errors
(exit 0)

$ pnpm run build
(exit 0)

$ node packages/lexical-eslint-plugin/__tests__/integration/integration-test.mjs
Total tests: 4
Passed: 4

$ git diff --check
(exit 0)
```

A separate smoke harness against the built plugin passed 17 cases on each
of ESLint 8.0.0, 8.36.0, 8.37.0, 8.39.0, 8.40.0, 9.39.5 and 10.14.0.
It compares diagnostics, locations, fixes and suggestions across versions,
excluding the nodeType field removed by ESLint 10. Cases include resolved,
unresolved and shadowed editor bindings, cross-editor updates, transform
and $function guidance with options, both read overloads and async contexts.

Validated on macOS with Node 26. Browser-mode and E2E matrices were not run
for this ESLint-only follow-up.

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. The scopeManager fallback makes the rule work on ESLint 8 before 8.37. Loaded into real ESLint 8.0.0, 8.27.0 and 8.36.0 Linters, it gives the same diagnostics as 8.37.0 and 10.11.0 across same-binding, shadowed, cross-editor, $function, transform, read and async cases. The new compatibility tests also fail against the previous version of the rule, so they guard the fix. The conditional $function wording and the transform message with the preconditions link cover the earlier suggestions. The @lexical/list, @lexical/react and playground rewrites keep their update tags and commit timing, and the Find/Replace tests still fail if $flushSyncAfterUpdate() is removed.

The GitHub workflows for this head are still waiting for approval, so CI hasn't run yet.

Optional, non-blocking suggestions

  • When you rebase onto current main: #9862 added a $retokenizeOldTokens helper that opens its own editor.update(…, {discrete: true}). It lives in packages/lexical-code-prism/src/__tests__/unit/CodePrismRetokenizeKeepsState.test.ts (line 816 on main) and packages/lexical-code-shiki/src/__tests__/unit/CodeShikiRetokenizeKeepsState.test.ts (line 840). Since eslint.config.mjs:351 sets this rule to error, lint on the merged tree reports both, and nothing else. Renaming the helper to retokenizeOldTokens (three call sites per file) keeps lint green, as this PR already does for pasteHtml and runOutdentScenario. AGENTS.md's "$ Functions Convention" reserves the prefix for functions that run inside an existing update or read.
  • Nit, packages/lexical-eslint-plugin/src/index.ts:27 and :39: the new keys on the exported FlatConfig.rules and Plugin.rules interfaces are required. An object that someone annotates as FlatConfig or Plugin with only the old keys would stop type checking, which .changeset/README.md ("Type signature changes") counts as breaking. Marking the two new keys optional (?:) avoids that.

Automated review (maintainer link)

Comment thread eslint.config.mjs
lexicalPlugin.configs['flat/all'],
{
rules: {
'@lexical/no-nested-editor-updates': ERROR,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, for the rebase: #9862 on main added a $retokenizeOldTokens helper that opens its own editor.update(…, {discrete: true}), in packages/lexical-code-prism/src/__tests__/unit/CodePrismRetokenizeKeepsState.test.ts (line 816) and packages/lexical-code-shiki/src/__tests__/unit/CodeShikiRetokenizeKeepsState.test.ts (line 840). With this ERROR, lint on the head merged into current main reports both, and nothing else. Renaming the helper to retokenizeOldTokens (three call sites per file), as this PR does for pasteHtml and runOutdentScenario, keeps it green.

'@lexical': Plugin;
};
rules: {
'@lexical/no-nested-editor-updates': 'warn' | 'error' | 'off';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this key, and 'no-nested-editor-updates' on Plugin.rules at line 39, are required. An object someone annotates as FlatConfig or Plugin with only the old keys would stop type checking, which .changeset/README.md ("Type signature changes") counts as breaking. Marking the two new keys optional (?:) avoids that.

Resolved packages/lexical-eslint-plugin/src/LexicalEslintPlugin.js: kept both
rule typedefs, this branch's '@lexical/no-nested-editor-updates' and main's
'@lexical/y-collab-status'.
@potatowagon

Copy link
Copy Markdown
Contributor

Merged latest main into this branch to clear the merge conflict, on behalf of @potatowagon, so this approved PR is mergeable again. Pushed as a merge commit (aedef76e8), not a rebase — your 10 commits are untouched and the review delta is unchanged.

Conflict: packages/lexical-eslint-plugin/src/LexicalEslintPlugin.js (1 hunk) — this branch added the @lexical/no-nested-editor-updates rule to the FlatConfig/Rules typedefs while main added @lexical/y-collab-status in the same lines.

Resolution: kept both, in alphabetical order. No behaviour change; the rules map below already registers all four rules.

Verified: full vitest --project unit suite — 36330 passed / 0 failed, against 36311 passed / 0 failed on plain main at da389d036. The one failing file in both runs is a pre-existing SIGSEGV in LexicalCharacterLimitPlugin.test.tsx, unrelated to this change. packages/lexical-eslint-plugin on its own: 43/43.

@pkg-pr-new

pkg-pr-new Bot commented Nov 17, 2026

Copy link
Copy Markdown
lexical

npm i https://pkg.pr.new/lexical@9106

@lexical/a11y

npm i https://pkg.pr.new/@lexical/a11y@9106

@lexical/clipboard

npm i https://pkg.pr.new/@lexical/clipboard@9106

@lexical/code

npm i https://pkg.pr.new/@lexical/code@9106

@lexical/code-core

npm i https://pkg.pr.new/@lexical/code-core@9106

@lexical/code-prism

npm i https://pkg.pr.new/@lexical/code-prism@9106

@lexical/code-shiki

npm i https://pkg.pr.new/@lexical/code-shiki@9106

@lexical/compiler

npm i https://pkg.pr.new/@lexical/compiler@9106

@lexical/devtools-core

npm i https://pkg.pr.new/@lexical/devtools-core@9106

@lexical/dragon

npm i https://pkg.pr.new/@lexical/dragon@9106

@lexical/eslint-plugin

npm i https://pkg.pr.new/@lexical/eslint-plugin@9106

@lexical/extension

npm i https://pkg.pr.new/@lexical/extension@9106

@lexical/fast-check

npm i https://pkg.pr.new/@lexical/fast-check@9106

@lexical/file

npm i https://pkg.pr.new/@lexical/file@9106

@lexical/hashtag

npm i https://pkg.pr.new/@lexical/hashtag@9106

@lexical/headless

npm i https://pkg.pr.new/@lexical/headless@9106

@lexical/history

npm i https://pkg.pr.new/@lexical/history@9106

@lexical/html

npm i https://pkg.pr.new/@lexical/html@9106

@lexical/internal

npm i https://pkg.pr.new/@lexical/internal@9106

@lexical/link

npm i https://pkg.pr.new/@lexical/link@9106

@lexical/list

npm i https://pkg.pr.new/@lexical/list@9106

@lexical/mark

npm i https://pkg.pr.new/@lexical/mark@9106

@lexical/markdown

npm i https://pkg.pr.new/@lexical/markdown@9106

@lexical/mdast

npm i https://pkg.pr.new/@lexical/mdast@9106

@lexical/offset

npm i https://pkg.pr.new/@lexical/offset@9106

@lexical/overflow

npm i https://pkg.pr.new/@lexical/overflow@9106

@lexical/plain-text

npm i https://pkg.pr.new/@lexical/plain-text@9106

@lexical/react

npm i https://pkg.pr.new/@lexical/react@9106

@lexical/rich-text

npm i https://pkg.pr.new/@lexical/rich-text@9106

@lexical/selection

npm i https://pkg.pr.new/@lexical/selection@9106

@lexical/table

npm i https://pkg.pr.new/@lexical/table@9106

@lexical/tailwind

npm i https://pkg.pr.new/@lexical/tailwind@9106

@lexical/text

npm i https://pkg.pr.new/@lexical/text@9106

@lexical/utils

npm i https://pkg.pr.new/@lexical/utils@9106

@lexical/y

npm i https://pkg.pr.new/@lexical/y@9106

@lexical/yjs

npm i https://pkg.pr.new/@lexical/yjs@9106

commit: aedef76

@rootnode-bot rootnode-bot Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, the change looks good. The rule's advice matches how Lexical runs same-editor updates: command listeners already run inside an update for their editor, and a nested update drains into the same pending state. The cleanups in @lexical/list and @lexical/react commit the same state, tags and timing as before. Turning the rule on as a warning in the default presets follows the maintainer direction from the earlier review.

Needed before merge (CI):

  • packages/lexical-code-prism/src/__tests__/unit/CodePrismRetokenizeKeepsState.test.ts:816 and packages/lexical-code-shiki/src/__tests__/unit/CodeShikiRetokenizeKeepsState.test.ts:840: the $retokenizeOldTokens helper that came in with the latest merge of main (#9862) opens its own editor.update(…, {discrete: true}). This PR's own rule, set to error in eslint.config.mjs, reports both calls, so pnpm run lint and the core-tests / integrity job fail. Rename the helper to retokenizeOldTokens (the definition plus three call sites in each file), as this PR already does for pasteHtml and runOutdentScenario; both files then lint clean. AGENTS.md lists both pnpm run lint and pnpm run ci-check (which runs ESLint) under Code Quality.

Optional, non-blocking:

  • packages/lexical-eslint-plugin/src/rules/no-nested-editor-updates.js:113 (getUpdateOptionMigrations): the options diagnostic looks only at keys. So editor.update(fn, {discrete: isSync}) is told to apply $flushSyncAfterUpdate unconditionally, which would force a synchronous commit when isSync is false. The README already says to call it only when discrete is true. Saying so in the message, or skipping non-literal discrete values, would carry that caveat into the diagnostic.

The two Find/Replace …synchronously tests do pin the preserved synchronous commit: without the $flushSyncAfterUpdate() calls in FindReplaceExtension/index.tsx they fail, and with them they pass.

Automated review (maintainer link)

@potatowagon

Copy link
Copy Markdown
Contributor

Heads-up on the core-tests / integrity (24.x) failure after I merged main in — it is not a merge-resolution problem, it is a real interaction this PR now has with main.

pnpm run lint fails with this PR's own new rule:

816:3  error  $retokenizeOldTokens is named as a Lexical $function but calls editor.update ...  @lexical/no-nested-editor-updates
840:3  error  $retokenizeOldTokens is named as a Lexical $function but calls editor.update ...  @lexical/no-nested-editor-updates

$retokenizeOldTokens is a test helper added to main by #9862 (c4bfbfc23), after this PR was approved, in:

  • packages/lexical-code-prism/src/__tests__/unit/CodePrismRetokenizeKeepsState.test.ts
  • packages/lexical-code-shiki/src/__tests__/unit/CodeShikiRetokenizeKeepsState.test.ts

It deliberately wraps editor.update, so by the rule's own second remedy the fix is to drop the $ prefix on that helper rather than to add discrete/$flushSyncAfterUpdate. I have not made that change — it is outside the conflict and is the author's call.

The branch is otherwise mergeable and its unit tests are green (36330 passed / 0 failed, against 36311 / 0 on main @ da389d036). cc @potatowagon

@rootnode-bot

rootnode-bot Bot commented Nov 17, 2026

Copy link
Copy Markdown

In reply to @potatowagon

I'll run a full review to re-check this with your note.

This branch was successfully deployed

2 active deployments
Preview – lexical — aedef76e Deployed Nov 17, 2026 by vercel[bot]
Preview – lexical-playground — aedef76e Deployed Nov 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Implement lint rule to eliminate accidental nested updates

3 participants